# -*- coding: utf-8 -*-
from flask_wtf import FlaskForm as Form
from wtforms import StringField, PasswordField, SubmitField, BooleanField, \
    SelectField
from wtforms.validators import DataRequired, Length, Email, EqualTo
from wtforms.validators import ValidationError

from ..models import User


class LoginForm(Form):
    username = StringField(u'邮箱', validators=[DataRequired(), Length(1, 64),
                                             Email()])
    password = PasswordField(u'密码', validators=[DataRequired()])
    remember_me = BooleanField(u'记住我')
    submit = SubmitField(u'登录')


class RegisterForm(Form):
    nickname = StringField(u'昵称', validators=[DataRequired(), Length(3, 15)])
    username = StringField(u'邮箱', validators=[DataRequired(), Length(1, 64),
                                              Email()])
    password = PasswordField(u'密码', validators=[DataRequired()])
    confirm_password = PasswordField(u'确认密码',
                                     validators=[DataRequired(),
                                     EqualTo('password', message=u'确认密码与密码不相同。')])
    role = SelectField(u'角色', coerce=int, validators=[DataRequired()])
    status = SelectField(u'状态', coerce=int)
    submit = SubmitField(u'创建')

    def validate_username(self, field):
        if User.query.filter_by(username=field.data).first():
            raise ValidationError(u'邮箱已经注册。')

    def validate_nickname(self, field):
        if User.query.filter_by(nickname=field.data).first():
            raise ValidationError(u'昵称已经被使用。')